package com.manager.util;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * @since jdk1.8
 */
public class JwtUtil {
    private static final long tokenExpiration = 24*60*60*1000;
    private static final String tokenSignKey = "123456";


    //根据传入参数创建token字符串
    public static String createToken(String memberName, String account) {
        return Jwts.builder()
                .setSubject("template")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .claim("memberName", memberName)
                .claim("account", account)
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
    }

    //根据token获取设置的key值
    public static String getMemberName(String token) {
        if(StringUtils.isEmpty(token)) return null;
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return (String) claims.get("memberName");
    }
    //根据token获取设置的key值
    public static String getAccount(String token) {
        if(StringUtils.isEmpty(token)) return "";
        Jws<Claims> claimsJws
                = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return (String)claims.get("account");
    }

}
